package com.synjones.pay.web.biz.client;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author hsd
 */
public class HttpClientUtils {

    private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class);

    public static String httpPost(String url, Map paramMap, String enCode) {
        
        log.info("GetPage:{}", url);
        String content = null;
        if (url == null || url.trim().length() == 0 || paramMap == null
                || paramMap.isEmpty()) {
            return null;
        }
        HttpClient httpClient = new HttpClient();
        //设置header
        httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2");//
        //代理设置
        PostMethod method = new PostMethod(url);
        Iterator it = paramMap.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next() + "";
            Object o = paramMap.get(key);
            if (o != null && o instanceof String) {
                method.addParameter(new NameValuePair(key, o.toString()));
            }
            if (o != null && o instanceof String[]) {
                String[] s = (String[]) o;
                if (null != s) {
                    for (int i = 0; i < s.length; i++) {
                        method.addParameter(new NameValuePair(key, s[i]));
                    }
                }
            }
        }
        try {
            int statusCode = httpClient.executeMethod(method);
           log.info("请求：{}\r\n 参数列表为：{} \r\n statusCode = {}", new Object[] { url, paramMap.toString(), statusCode});
           log.info("statusLine:{}", method.getStatusLine());
            content = new String(method.getResponseBody(), enCode);
        } catch (IOException e) {
            log.error("time out:{}", e);
            return null;
        } finally {
            method.releaseConnection();
        }
        return content;
    }
    
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("ticket", "123");
        httpPost("http://localhost:8080/api/wx/getCardInfoByTicket",map,"UTF-8");         
    }
}
